chrome.storage.sync.get(["status"], res => {
	if (!res || res.status !== 'false'){
		setTimeout(()=>{
			startNewChapter()
		}, 500)
	}else {
		console.log("CX->自动刷课未打开")
	}
})


var videoUrl = null;
var loadVideoTime = 1000;
var watchTask;
//看视频
let watch = function (){
	const iframe = document.getElementById("iframe");
	if(!iframe || !iframe.contentDocument){
		console.info("CX->找不到iframe")
		return;
	}
	const one = iframe.contentDocument;
	const ans_insertvideo_online = one.getElementsByClassName("ans-insertvideo-online");
	if (!ans_insertvideo_online || ans_insertvideo_online.length === 0 || !ans_insertvideo_online[0].contentDocument){
		console.info("CX->找不到ans_insertvideo_online")
		return;
	}
	const two = ans_insertvideo_online[0].contentDocument;
	const video = two.getElementById("video_html5_api")
	if (!video){
		console.info("CX->找不到video")
		return;
	}else if (videoUrl != null && videoUrl === video.currentSrc){
		return;
	}
	const finished = one.getElementsByClassName("ans-job-finished");
	if (!finished || finished.length > 0){
		console.info("CX->当前视频看过了，准备做题")
		completeChapter();
		return;
	}
	console.info("CX->视频准备中")
	video.muted = true;
	video.load();
	videoUrl = video.currentSrc;
	setTimeout(() => {
		console.info("CX->视频开始播放")
		video.play();
	}, loadVideoTime)//等待视频加载完毕（用video的加载完毕监听会弹出验证界面），网速较慢时需要增大此值
	video.addEventListener('ended', () => {
		console.info("CX：视频播放完毕,准备做题,", new Date().toLocaleString());
		completeChapter()
	}, false);
	//视频永不停止播放
	video.addEventListener('pause', () => {
		video.play();
	})
}

//做题
function completeChapter(){
	clearInterval(watchTask)
	setTimeout(()=>{
		nextChapter()
		const i = document.getElementById("iframe");
		if (!i){
			return;
		}
		i.onload = ()=>{
			console.info("CX->题目加载完毕")
			//todo 搜题 有题库后再做
			console.info("CX->不做题")
			//继续学习下一章
			setTimeout(() => {
				const nextChapter = document.getElementsByClassName("nextChapter");
				if (nextChapter && nextChapter.length > 0){
					nextChapter[0].removeAttribute("href")
					nextChapter[0].click()
				}
				startNewChapter()
			}, 1000)//防止操作过快被认为是脚本
		}
	}, 1000)//防止操作过快被认为是脚本
}
function nextChapter(){
	const next = document.querySelectorAll(".next");
	if (!next || next.length === 0){
		console.info("CX->找不到下一章按钮")
		return
	}
	next[0].click()
}
function startNewChapter(){
	const title = document.getElementsByClassName("prev_title");
	if (!title || title.length === 0){
		console.info("CX->找不到title")
		setTimeout(() => {
			startNewChapter()
		}, 500)
		return;
	}
	const titleContext = title[0].innerText;
	if (titleContext.indexOf('单元测验') !== -1){
		console.info("CX->单元测试跳过")
		nextChapter()
	}else if (titleContext.indexOf('课程预习') !== -1){
		console.info("CX->课程预习跳过")
		nextChapter()
	}else if (titleContext.indexOf('讨论') !== -1){
		console.info("CX->讨论跳过")
		nextChapter()
	}else if (titleContext.indexOf("直播课") !== -1){
		console.info("CX->直播课跳过")
		nextChapter()
	}else{
		watchTask = setInterval(watch, 1000)
	}
}
